﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using VH.SharePoint.Api.Helpers;
using VH.SharePoint.Api.Queries;

namespace VH.SharePoint.Api.SharePoint
{
    public class SPPostRepository : PostRepository
    {
        private BlogWeb Blog { get; set; }
        public override IEnumerable<MetaWeblog.Post> FindAll()
        {
            return Blog.GetPosts().Select(p => GetPostFromBlog(p)).ToList();
        }

        public override IEnumerable<MetaWeblog.Post> FindAll(Queries.QueryConstraints<MetaWeblog.Post> constraints)
        {
            var posts = Blog.GetPosts();
            posts.Query.RowLimit = (uint)constraints.PageSize;
            var results = this.FindAll().AsQueryable();
            return constraints.ApplyTo(results).ToList();
        }

        public override MetaWeblog.Post Get(string id)
        {
            var posts = Blog.GetPosts();
            var post = posts[int.Parse(id)];
            return GetPostFromBlog(post);
        }

        public override void Create(MetaWeblog.Post entity)
        {
            var posts = Blog.GetPosts();
            var post = posts.Add(new PostItemInfo
                {
                    Title = entity.Title
                });
            entity.Id = post.Id;
            SetContent(post, entity);
        }

        public override void Publish(MetaWeblog.Post entity, bool publish)
        {
            var posts = Blog.GetPosts();
            var post = posts[entity.Id];
            if (publish)
                post.Publish();
        }

        public override void Update(MetaWeblog.Post entity)
        {
            var posts = Blog.GetPosts();
            var post = posts[entity.Id];
            SetContent(post, entity);
            
        }

        public override void Delete(MetaWeblog.Post entity)
        {
            var posts = Blog.GetPosts();
            posts.Delete(entity.Id);
        }

        public override void ValidateUser(string username, string password)
        {
           
        }

        public SPPostRepository(BlogWeb blogWeb)
        {
            Blog = blogWeb;
        }

        private void SetContent(PostItem post, MetaWeblog.Post entity)
        {
            using (new SPUnsafeUpdate(Blog.Web))
            {
                post.Title = entity.Title;
                
                var wrappedContent = entity.Description;
                if (WlwHelper.IsRequestedByWlw())
                {
                    var mediaslist = Blog.Web.Lists[Blog.MediaLibraryId];
                    wrappedContent = WlwHelper.WrapUploadContent(wrappedContent, mediaslist.RootFolder.Name + "/" + Blog.MediaFolderName);
                }
                if (Blog.ScriptTagsEnabled)
                {
                    var file = post.File;
                    if (file.CheckOutType == SPFile.SPCheckOutType.None){
                        file.CheckOut();
                    }
                    wrappedContent = PageHelper.WrapSrciptTagIntCewp(file, wrappedContent);

                    file.Update();
                    file.CheckIn(string.Empty);
                    
                    post = file.Item;
                }
                post.Content = wrappedContent;
                post.Update();
            }
            
        }

        private string GetContent(PostItem post)
        {
            var content = post.Content;

            content = PageHelper.GetEditableContent(post.File, content);

            return content;
        }

        private MetaWeblog.Post GetPostFromBlog(PostItem item)
        {
            var post = new MetaWeblog.Post();
            post.Id = item.Id;
            post.Title = item.Title;
            post.Created = item.Created;
            post.Modified = item.Modified;
            var author = item.CreatedBy;
            post.AuthorDisplayName = author.Name;
            post.AuthorId = author.ID.ToString(CultureInfo.InvariantCulture);
            post.Status = item.Status.ToString();
            post.Published = item.Published;
            post.Description = GetContent(item);
            post.Url = item.Url;
            post.PermaLink = item.Url;
            return post;
        }
    }
}
